package com.vegetable.modules.service.sys.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.sys.SysUserEntity;
import com.vegetable.modules.entity.sys.SysUserTokenEntity;
import com.vegetable.modules.mapper.sys.SysUserTokenDao;
import com.vegetable.modules.oauth2.TokenGenerator;
import com.vegetable.modules.service.sys.SysUserTokenService;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
	//一周后过期
	private final static int EXPIRE = 3600 * 24 * 7;


	@Override
	public R createToken(long userId) {
		return createToken(userId, "");
	}

	@Override
	public R createToken(long userId, String mobile) {
		return createToken(userId, mobile, 0);
	}

	@Override
	public R createToken(long userId, String mobile, Integer userType) {
		//生成一个token
		String token;

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		SysUserTokenEntity tokenEntity = this.getById(userId);
		if(tokenEntity == null){
			//生成一个token
			token = makeToken(userType);
			tokenEntity = new SysUserTokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setMobile(mobile);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			tokenEntity.setUserType(userType);
			//保存token
			this.save(tokenEntity);
		}else{
//			tokenEntity.setToken(token);
			token = tokenEntity.getToken();
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			this.updateById(tokenEntity);
		}
		return R.data(token);
	}

	private static String makeToken(Integer userType) {
		String token = TokenGenerator.generateValue();
		if(userType == 1){
			token = token + ":visitor";
		}
		return token;
	}

	@Override
	public R createToken(SysUserEntity userEntity) {
		return createToken(userEntity.getUserId(), userEntity.getMobile(), userEntity.getUserType());
	}


	@Override
	public void logout(long userId) {
		//生成一个token
//		String token = TokenGenerator.generateValue();
//
//		//修改token
//		SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
//		tokenEntity.setUserId(userId);
//		tokenEntity.setToken(token);
		this.baseMapper.deleteById(userId);
	}
}
